import { defineStore } from "pinia";
import request from "@/utils/request";
import message from "@/utils/message";
import { RequestParams } from "@/types/request";
import api from "@/utils/api";
import { AxiosRequestHeaders } from "axios";
import { PatientInfo } from "@/types/patient";

export const usePatientDiagnosisStore = defineStore("patientDiagnosis", {
  state: (): {
    patientInfo: PatientInfo;
  } => ({
    patientInfo: {} as PatientInfo,
  }),
  actions: {
    async login(loginParams: RequestParams) {
      try {
        let result: any = await request({
          method: "post",
          url: api.patientsLogin,
          data: loginParams as RequestParams,
          headers: {
            "Content-Type": "application/json",
          } as AxiosRequestHeaders,
        });
        if (!result) {
          return;
        }
        if (result.code === 1) {
          this.patientInfo = result.data;
          message.success("登录成功");
          let patientData: PatientInfo = {} as PatientInfo;
          patientData = result.data;
          sessionStorage.setItem("patientData", JSON.stringify(patientData));
          return result;
        } else {
          message.error("登陆失败，请检查帐号密码");
        }
      } catch (error) {
        message.error("登录异常");
      }
    },
    async register(registerParams: RequestParams) {
      try {
        let result: any = await request({
          method: "post",
          url: api.patientsRegister,
          data: registerParams as RequestParams,
          headers: {
            "Content-Type": "application/json",
          } as AxiosRequestHeaders,
        });
        if (!result) return;
        if (result.code === 1) {
          message.success("注册成功");
          //跳转患者登录
          this.patientInfo = registerParams as PatientInfo;
          return result;
        } else {
          message.error("注册失败，请检查相关信息");
        }
      } catch (error) {
        message.error("注册异常");
      }
    },
    getPatientInfo() {
      if (!this.patientInfo) {
        const storedData = sessionStorage.getItem("patientData");
        if (storedData) {
          this.patientInfo = JSON.parse(storedData);
        }
      }
      return this.patientInfo;
    },
    setPatientInfo(username: string) {
      if (this.patientInfo) {
        this.patientInfo.username = username;
        sessionStorage.setItem("patientData", JSON.stringify(this.patientInfo));
      }
    },
  },
});
